package com.qubuyer.business.order.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.alipay.sdk.app.PayTask
import com.qubuyer.R
import com.qubuyer.bean.event.WechatPayStatusEvent
import com.qubuyer.bean.payment.AliPayResultEntity
import com.qubuyer.business.order.PayOrderViewModel
import com.qubuyer.business.payment.activity.PaymentResultFragment
import com.qubuyer.core.app.MVVMFragment
import com.qubuyer.core.ext.format
import com.qubuyer.databinding.FragmentOrderNowPayBinding
import com.qubuyer.utils.TimeUtil
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.Subscribe

/**
 * @author Susong
 * @date 创建时间:2019/2/26
 * @description 订单立即付款页
 * & @version
 */
class OrderNowPayFragment : MVVMFragment<FragmentOrderNowPayBinding, PayOrderViewModel>() {

    override fun getTitle(): String {
        return "请选择支付方式"
    }

    override fun onDataBinding(dataBinding: FragmentOrderNowPayBinding) {
        dataBinding.host = this
    }

    override val viewModel: PayOrderViewModel by injectVMByActivity()

    override val layoutId: Int
        get() = R.layout.fragment_order_now_pay

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewDataBinding.tvWxPay.isSelected = true
        viewModel.mOrderEntity?.let {
            viewModel.orderId = it.order_id.toString()
            viewDataBinding.tvPayPrice.text = "实付款：¥${it.order_amount?.toDouble()?.format(2)}"
            val remainingTime = it.time_out * 1000 - System.currentTimeMillis()
            val seconds = remainingTime / 1000
            launch {
                (seconds downTo 0).asFlow().onEach { time ->
                    val timeMode = TimeUtil.parseRemainTime(time * 1000)
                    if (timeMode.day > 0) {
                        timeMode.hour = timeMode.hour + timeMode.day * 24
                    }
                    viewDataBinding.tvOverTime.text = "距订单关闭还有" + timeMode.hour + "小时" + timeMode.minute + "分钟"
                    delay(1000)
                }.collectLatest {
                    viewDataBinding.tvOverTime.text = "订单已关闭"
                }
            }
        }
        viewModel.mSOEntity?.let {
            viewModel.orderId = it.order_id
            viewDataBinding.tvPayPrice.text = "实付款：¥${it.order_amount?.toDouble()?.format(2)}"
        }
        viewModel.wxParams.observe(viewLifecycleOwner, {
            if (TextUtils.isEmpty(it.appid)
                    || TextUtils.isEmpty(it.partnerid)
                    || TextUtils.isEmpty(it.prepayid)
                    || TextUtils.isEmpty(it.noncestr)
                    || TextUtils.isEmpty(it.timestamp)
                    || TextUtils.isEmpty(it.sign)) {
                toast("支付参数不完整")
            } else {
                val api = WXAPIFactory.createWXAPI(mContext, it.appid)
                api.registerApp(it.appid)
                val payReq = PayReq()
                payReq.appId = it.appid
                payReq.partnerId = it.partnerid
                payReq.prepayId = it.prepayid
                payReq.packageValue = "Sign=WXPay"
                payReq.nonceStr = it.noncestr
                payReq.timeStamp = it.timestamp
                payReq.sign = it.sign
                api.sendReq(payReq)
            }
        })
        viewModel.aliParams.observe(viewLifecycleOwner, { params ->
            if (TextUtils.isEmpty(params)) {
                toast("支付参数不完整")
            } else {
                launch {
                    val payResult = withContext(Dispatchers.IO) {
                        AliPayResultEntity(PayTask(mContext).payV2(params, true))
                    }

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        viewModel.getOrderPayResult()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        toast(payResult.memo)
                    }
                }
            }
        })
        viewModel.payResult.observe(viewLifecycleOwner, {
            mContext.swapContentFragment(PaymentResultFragment())
        })
    }

    @Subscribe
    fun onEvent(event: WechatPayStatusEvent) {
        if (event.status == 1) {
            viewModel.getOrderPayResult()
        }
    }

    fun onClick(v: View) {
        when (v.id) {
            R.id.tvWxPay -> {
                viewDataBinding.tvAliPay.isSelected = false
                viewDataBinding.tvWxPay.isSelected = true
                viewModel.payType = 1
            }
            R.id.tvAliPay -> {
                viewDataBinding.tvAliPay.isSelected = true
                viewDataBinding.tvWxPay.isSelected = false
                viewModel.payType = 2
            }
            R.id.tv_now_pay -> {
                mContext.swapContentFragment(PaymentResultFragment())
//                if (viewModel.orderId.isNullOrEmpty()) {
//                    toast("订单数据异常")
//                    return
//                }
//                viewModel.pay()
            }
        }
    }
}